package com.sankuai.inf.leaf.snowflake;

import com.google.common.base.Preconditions;
import com.sankuai.inf.leaf.IDGen;
import com.sankuai.inf.leaf.common.Result;
import com.sankuai.inf.leaf.common.Status;
import com.sankuai.inf.leaf.common.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Random;

public class SnowflakeIDGenImpl implements IDGen {

    @Override
    public boolean init() {
        return true;
    }

    private static final Logger LOGGER = LoggerFactory.getLogger(SnowflakeIDGenImpl.class);

    private final long twepoch;//起始时间戳
    private final long workerIdBits = 10L;// 工作机器码位数
    private final long maxWorkerId = ~(-1L << workerIdBits);//最大能够分配的workerid =1023
    private final long sequenceBits = 12L;// 同一毫秒内的最大序号占用二进制位数
    private final long workerIdShift = sequenceBits;// 机器码向左偏移12位
    private final long timestampLeftShift = sequenceBits + workerIdBits;// 时间戳偏移22位
    private final long sequenceMask = ~(-1L << sequenceBits);// 同一毫秒内的最大序号值4095
    private long workerId;//机器码
    private long sequence = 0L;//序号
    private long lastTimestamp = -1L;//上次生成的时间戳
    private static final Random RANDOM = new Random();

    public SnowflakeIDGenImpl(String zkAddress, int port) {
        // Thu Nov 04 2010 09:42:54 GMT+0800 (中国标准时间)
        // 此处可以自定义，比如2020-01-01 00:00:00对应的long类型值为：1577808000000L
        this(zkAddress, port, 1288834974657L);
    }

    /**
     * @param zkAddress zk地址
     * @param port      snowflake监听端口
     * @param twepoch   起始的时间戳
     */
    public SnowflakeIDGenImpl(String zkAddress, int port, long twepoch) {
        this.twepoch = twepoch;// 起始时间戳赋值
        // 起始时间戳不能大于当前时间戳
        Preconditions.checkArgument(timeGen() > twepoch, "Snowflake not support twepoch gt currentTime");
        final String ip = Utils.getIp();// 获取本机IP（第一个网卡的IP）
        SnowflakeZookeeperHolder holder = new SnowflakeZookeeperHolder(ip, String.valueOf(port), zkAddress);
        LOGGER.info("twepoch:{} ,ip:{} ,zkAddress:{} port:{}", twepoch, ip, zkAddress, port);
        boolean initFlag = holder.init();
        if (initFlag) {
            // 获取机器码
            workerId = holder.getWorkerID();
            LOGGER.info("START SUCCESS USE ZK WORKERID-{}", workerId);
        } else {
            Preconditions.checkArgument(initFlag, "Snowflake Id Gen is not init ok");
        }
        // 校验机器码是否在0到1023之间
        Preconditions.checkArgument(workerId >= 0 && workerId <= maxWorkerId, "workerID must gte 0 and lte 1023");
    }

    @Override
    public synchronized Result get(String key) {
        // 获取机器当前时间戳
        long timestamp = timeGen();
        // 当前时间戳小于上次生成时间戳，说明发生了时钟回拨
        // 该算法只允许5毫秒以内的时钟回拨，超出则返回异常结果
        // 实际的项目中可以根据情况适当改变策略
        if (timestamp < lastTimestamp) {
            // 获取时钟回拨的值
            long offset = lastTimestamp - timestamp;
            // 回拨值 <= 5毫秒
            if (offset <= 5) {
                try {
                    // 等待双倍的时间，offset << 1等价于offset * 2
                    wait(offset << 1);
                    // 再次取得当前时间戳
                    timestamp = timeGen();
                    // 当前时间戳依然小于上次时间戳（等待期间又发生了时钟回拨），则返回异常结果
                    if (timestamp < lastTimestamp) {
                        return new Result(-1, Status.EXCEPTION);
                    }
                } catch (InterruptedException e) {
                    LOGGER.error("wait interrupted");
                    return new Result(-2, Status.EXCEPTION);
                }
            } else {// 回拨值大于5毫秒时，直接返回异常结果
                return new Result(-3, Status.EXCEPTION);
            }
        }
        // 同一毫秒内
        if (lastTimestamp == timestamp) {
            // 序号+1
            sequence = (sequence + 1) & sequenceMask;
            // 序号超过最大值
            if (sequence == 0) {
                //seq 为0的时候表示是下一毫秒时间开始对seq做随机
                sequence = RANDOM.nextInt(100);
                // 等到下一毫秒
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            //如果是新的ms开始
            sequence = RANDOM.nextInt(100);
        }
        // 上次生成时间戳赋予新值，即当前时间戳
        lastTimestamp = timestamp;
        // 二进制移位拼接，获得long类型的id
        long id = ((timestamp - twepoch) << timestampLeftShift) | (workerId << workerIdShift) | sequence;
        return new Result(id, Status.SUCCESS);

    }

    /**
     * 等待并获取指定时间戳下一毫秒的时间戳
     *
     * @param lastTimestamp
     */
    protected long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    /**
     * 获取当前时间戳：System.currentTimeMillis()
     */
    protected long timeGen() {
        return System.currentTimeMillis();
    }

    public long getWorkerId() {
        return workerId;
    }

}
